package com.fingard.dsp.bank.directbank.abc11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.util.Date;

public class ABC11BatPayRec extends ABC11Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPay(p_req1998);
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPay(p_req9198);
    }

    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);

        StringBuilder tmpMsg = new StringBuilder();
        String separator = "|";
        //文件第一行：（汇总信息）
        //格式：保险公司代码|银行代码|总记录数|总金额|交易摘要
        tmpMsg.append(bankFront.corpNo).append(separator);
        tmpMsg.append(p_reqBat.ownBankCode).append(separator);
        tmpMsg.append(p_reqBat.totalNum).append(separator);
        tmpMsg.append(p_reqBat.totalAmt).append(separator);
        tmpMsg.append(p_reqBat.useType);
        tmpMsg.append("\r\n");

        while (p_reqBat.readRecord()) {
            //文件其他内容：（明细记录）
            //交易日期|明细顺序号|客户账号|客户名称|证件类型|证件号码|保单号|账户省市代码|币种|交易金额
            tmpMsg.append(Format.Date8Format.format(p_reqBat.getPayDateOnly())).append(separator);
            if (p_reqBat.reqHeader.transType.equals("1988")) {
                tmpMsg.append(p_reqBat.readedDetail.askNumber).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.payAct).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.payName).append(separator);
                tmpMsg.append(convertCertTypeToBank(p_reqBat.readedDetail.certType)).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.certNum).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.sourceNoteCode).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.payArea.substring(0,2)).append(separator);
                tmpMsg.append(convertCurToBank(p_reqBat.readedDetail.payCur)).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.payAmount);
            } else if (p_reqBat.reqHeader.transType.equals("9188")) {
                tmpMsg.append(p_reqBat.readedDetail.askNumber).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.recAct).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.recName).append(separator);
                tmpMsg.append(convertCertTypeToBank(p_reqBat.readedDetail.certType)).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.certNum).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.sourceNoteCode).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.recArea.substring(0,2)).append(separator);
                tmpMsg.append(convertCurToBank(p_reqBat.readedDetail.recCur)).append(separator);
                tmpMsg.append(p_reqBat.readedDetail.payAmount);
            }
            tmpMsg.append("\r\n");
        }

        String type = "";
        if (p_reqBat.reqHeader.transType.equals("1988")) {
            type = "1";
        } else if (p_reqBat.reqHeader.transType.equals("9188")) {
            type = "0";
        }
        //文件名：BATCH*$.YYYYMMDD
        //其中:*（1位）：0-批量代收；1-批量代付
        //     $（4位）：保险公司代码（银行定义）
        //     YYYYMMDD（8位）：交易日期
        String tmpUploadFileName = "BATCH" + type + bankFront.corpNo + "." + Format.Date8Format.format(p_reqBat.getPayDateOnly());
        String path = createTempFileDirectory() + File.separator + tmpUploadFileName;
        WriteBankLogLn2("批次请求文件保存本机路径: " + path);

        if (FileHelper.existFile(path)) {
            retAts.respCode = "0";
            retAts.respInfo = "本地批次文件[" + path + "]已上传,请勿重复上传!";
            retAts.reqSeqID = p_reqBat.reqBatchNO;
            retAts.transState = PaymentState.FAIL_Batch;
            retAts.payInfoCode = FailCode.E9981;
            retAts.writeRetToATS();
            return retAts;
        }
        FileHelper.writeFile(path, tmpMsg.toString(), getCharset());
        FtpSet ftpSet = bankFront.getFtpSet("batPayRec");
        String directDir = "";
        if(getBankConfig().getValueAsBool("useDateFtpPath")) {
            String tmpDate = Format.Date8Format.format(p_reqBat.getPayDateOnly());
            if (ftpSet.upDir.endsWith("/")) {
                directDir = tmpDate;
            } else {
                directDir = "/" + tmpDate;
            }
        }
        ftpSet.upDir = ftpSet.upDir + directDir;
        FtpReceiver ftpReceiver = sendToBank(path, tmpUploadFileName, ftpSet);
        if (ftpReceiver.isCompleted) {
            retAts.respCode = "0";
            retAts.respInfo = "支付文件上传成功";
            retAts.transState = "Uploaded";
            retAts.payInfoCode = "I4001";
        } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
            retAts.respCode = "0";
            retAts.respInfo = "支付文件上传失败";
            retAts.transState = "BatchFailed";
            retAts.payInfoCode = "E9999";
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = ftpReceiver.connMsg;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    public RetAtsQryBatPayRec d_QryBatPay(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;
        try {
            String type = "";
            if (p_reqQryBat.reqHeader.transType.equals("1998")) {
                type = "1";
            } else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
                type = "0";
            }
            //文件名：BATCHANS*$.YYYYMMDD
            //其中：*（1位）：0-批量代收；1-批量代付
            //      $（4位）：保险公司代码（银行定义）
            //　　　YYYYMMDD（8位）：交易日期
            Date tmpDateNow = getDayCutTime(p_reqQryBat.getBgnDateTime());
            String tmpDate = Format.Date8Format.format(tmpDateNow);
            String tmpDownFileName = "BATCHANS" + type + bankFront.corpNo + "." + tmpDate;
            String tmpResultFilePath = getTempFileDirectory(tmpDateNow) + File.separator + tmpDownFileName;
            WriteBankLogLn2("批次结果文件保存本地路径: " + tmpResultFilePath);
            FtpSet ftpSet = bankFront.getFtpSet("batPayRec");
            String directDir = "";
            if(getBankConfig().getValueAsBool("useDateFtpPath")) {
                if (ftpSet.downDir.endsWith("/")) {
                    directDir = tmpDate;
                } else {
                    directDir = "/" + tmpDate;
                }
            }
            ftpSet.downDir = ftpSet.downDir + directDir;
            FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
            FtpReceiver ftpReceiver = ftpPortClient.downloadFile(tmpDownFileName, tmpResultFilePath);
            if (ftpReceiver.isCompleted) {
                String tmpStrRet = FileHelper.readFileText(tmpResultFilePath, getCharset());
                WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);

                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    retAts.respCode = "0";
                    retAts.reqSeqID = p_reqQryBat.reqBatchNO;

                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);
                    tmpReader.readLine();

                    while(true) {
                        String eachline = tmpReader.readLine();
                        if(StringHelper.isNullOrEmpty(eachline)){
                            break;
                        }
                        String[] eachNodes = eachline.split("\\|");
                        if (eachNodes.length == 12) {
                            RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                            tmpRetDetail.postScript = eachNodes[1].trim();
                            if(p_reqQryBat.reqHeader.transType.equals("1998")){
                                tmpRetDetail.recAct = eachNodes[2].trim();
                                tmpRetDetail.recName = eachNodes[3].trim();
                            } else if(p_reqQryBat.reqHeader.transType.equals("9198")){
                                tmpRetDetail.payAct = eachNodes[2].trim();
                                tmpRetDetail.payName = eachNodes[3].trim();
                            }
                            tmpRetDetail.curType = convertCurToATS(eachNodes[8].trim());
                            tmpRetDetail.payAmount = eachNodes[9].trim();
                            tmpRetDetail.payInfoCode = eachNodes[10].trim();
                            tmpRetDetail.result = eachNodes[10].trim();
                            tmpRetDetail.memo = eachNodes[11].trim();
                            retAts.writeRetDetail(tmpRetDetail);
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "回盘文件明细长度不符，实际为：" + eachline.length();
                        }
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "回盘文件[" + tmpDownFileName + "]内容为空!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "回盘文件下载失败:" + ftpReceiver.connMsg;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeAfterDetail();
        return retAts;
    }
}
